﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Top.Api.Util;
using System.Text;

namespace CloudTaobao.Util
{
    public class LoginClient
    {
        public const string APP_KEY = "appkey";
        public const string FORMAT = "format";
        public const string METHOD = "api";
        public const string TIMESTAMP = "t";
        public const string VERSION = "v";
        public const string SIGN = "sign";
        public const string SIGN_METHOD = "sign_method";
        public const string PARTNER_ID = "partner_id";
        public const string SESSION = "session";
        public const string FORMAT_XML = "xml";
        public const string MD5 = "md5";
        public const string TTID = "ttid";

        //private const string serverUrl = "http://gw.api.tbsandbox.com/router/rest";
        private const string serverUrl = "http://api.m.taobao.com/rest/api2.do";
        private const string appKey = "12258862";
        //private const string appSecret = "sandbox06188e58800889532f557b8fe";
        private const string appSecret = "838101106188e58800889532f557b8fe";
        private const string ttid = "400000_12258862@yqft_windowsphone7_1.0.0";

        private Dictionary<string, string> txtParams = new Dictionary<string, string>();

        #region DefaultTopClient Constructors

        public LoginClient()
        {
            AppSettings settings = new AppSettings();
            if (settings.imei == "") {
                Random rd = new Random();
                int i = rd.Next();
                string x = i.ToString("x");
                string imei = "WPhone" + x.Substring(x.Length - 4, 4) + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                settings.imei = imei;
            }

            if (settings.imsi == "")
            {
                Random rd = new Random();
                int i = rd.Next();
                string x = i.ToString("x");
                string imsi = "WPhone" + x.Substring(x.Length - 4, 4) + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
                settings.imsi = imsi;
            }
        }

        #endregion

        #region ITopClient Members

        public void addParameter(string key, string value)
        {
            if (key != null && !key.Equals(""))
            {
                txtParams.Add(key, value);
            }
        }

        public Dictionary<string, string> getSortedDictionary(Dictionary<string, string> origin)
        {
            Dictionary<string, string> dict = (from entry in origin orderby entry.Key ascending select entry).ToDictionary(x => x.Key, x => x.Value);
            return dict;
        }

        public string buildQuery(Dictionary<string, string> parameters)
        {
            string query = "";
            IEnumerator<KeyValuePair<string, string>> textEnum = parameters.GetEnumerator();
            while (textEnum.MoveNext())
            {
                query += textEnum.Current.Key;
                query += "=";
                query += textEnum.Current.Value;
                query += "&";
            }
            query = query.Substring(0, query.Length - 1);
            return query;
        }

        public void sendRequest(AsyncCallback callback)
        {
            // 添加协议级请求参数
            //txtParams.Add(APP_KEY, appKey);
            if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                throw new NetException();
            AppSettings settings = new AppSettings();
            txtParams.Add("imei", settings.imei);
            txtParams.Add("imsi", settings.imsi);
            txtParams.Add(TTID, ttid);
            txtParams.Add(VERSION, "*");
            txtParams = getSortedDictionary(txtParams);
            // 添加签名参数
            if (txtParams["api"] != null && txtParams["api"].Equals("com.taobao.client.mtop.getUserSessionKey"))
            {
                txtParams.Add(SIGN, Convert.ToBase64String(MD5Core.GetHash(Encoding.UTF8.GetBytes(appKey + appSecret + txtParams["key"] + DateTime.Now.ToString()))));
            }
            else if (txtParams["api"] != null && txtParams["api"].Equals("com.taobao.wireless.mtop.getLoginUrl"))
            {
                txtParams.Add(SIGN, Convert.ToBase64String(MD5Core.GetHash(Encoding.UTF8.GetBytes(appKey + appSecret + DateTime.Now.ToString()))));
            }
            

            UriBuilder fullUri = new UriBuilder(serverUrl);

            //组装query字符串
            string query = buildQuery(txtParams);

            fullUri.Query = query;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);

            // set up the state object for the async request
            UpdateState state = new UpdateState();
            state.AsyncRequest = request;

            // start the asynchronous request
            request.BeginGetResponse(callback, state);

        }

        #endregion
    }
}
